const userMapper = require('@/mappers/userMapper');
const { setToken, getToken, generateVeryCode, generateUserId, filterObjectByKeys } = require('@/utils/index.js');
const redisClient = require('@/client/redisClient');
const bcrypt = require('bcryptjs');
const sendEmail = require('@/client/mailer');


async function createUser(user) {
    const { user_name, phone , password } = user;
    let hasUser = await findUser(phone);
    console.log("hasUser",hasUser)
    if(hasUser){
        throw new Error('用户已存在，请勿重复注册');
    }
    const id = generateUserId(user_name);
    // 生成盐值
    const salt = await bcrypt.genSalt(2); 
    const hashedPassword = await bcrypt.hash(password, salt);
    console.log("hashedPassword",hashedPassword)
    const result = await userMapper.createUser({...user,password:hashedPassword, uid:id });
    return result
}

async function findUser(phone) {
    const result = await userMapper.findUser(phone);
    return result
}


async function veryLogin({phone,password}) {
    const user = await userMapper.findUser(phone);
    if (!user) {
       throw new Error('用户还未注册')
    }
    const isPasswordValid = await bcrypt.compare(password, user.password);
    console.log("isPasswordValid",isPasswordValid)
    if (!isPasswordValid) {
        throw new Error('账户或密码错误')
    }

    const allowedFields = ['uid', 'phone', 'user_name'];
    const filteredUser = filterObjectByKeys(user, allowedFields);
    let uid = filteredUser.uid;
    await redisClient.set(uid, setToken(filteredUser), 'EX', 60 * 60 * 24 );
    const result =  {...filteredUser, token:setToken(user)}
    return result
}

async function loginOut(userId) {
        try{
            await redisClient.del(userId);
        }catch(e){
            throw new Error('退出失败')
        }
        return '退出成功！'
}



module.exports = { 
    createUser,
    veryLogin,
    loginOut
};